﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json;


namespace Best.SmartCms.Core.Caching
{
    /// <summary>Redis缓存</summary>
    public class Redis : Cache
    {
        private readonly RedisHelper _helper;
        public Redis()
        {
            _helper = new RedisHelper();
            _helper.SetPrefix(Prefix);
            Expire = 60 * 30;
        }

        /// <summary>
        /// 前缀
        /// </summary>
        public string Prefix { get; set; } = "SmartCms_";

        public override Int32 Count =>0;

        public override ICollection<string> Keys => null;
        public override bool ContainsKey(string key)
        {
            return _helper.KeyExists(key);
        }

        public override bool Set<T>(string key, T value, int expire = -1)
        {
            if (expire <= 0) expire = Expire;
            var timeSpan = TimeSpan.FromSeconds(expire);
            var jsonData = JsonConvert.SerializeObject(value); 
            return _helper.StringSet(key, jsonData, timeSpan);
        }

        public override T Get<T>(string key)
        {
            var cacheValue = _helper.StringGet(key);
            if (!string.IsNullOrEmpty(cacheValue))
            {
                return JsonConvert.DeserializeObject<T>(cacheValue);
            }

            return default(T);
        }



        public override int Remove(params string[] keys)
        {
            var count = 0;
            foreach (var key in keys)
            {
                if (_helper.KeyDelete(key))
                {
                    count++;
                }
            }

            return count;
        }

        public override bool SetExpire(string key, TimeSpan expire)
        {
           return _helper.KeyExpire(key, expire);
        }

        public override TimeSpan GetExpire(string key)
        {
            return _helper.KeyTimeToLive(key);
        }

        /// <summary>
        /// 判断key是否存在
        /// </summary>
        public bool Exists(string key)
        {
            return _helper.KeyExists(key);
        }
    }
}